import path from "path";
import fs from "fs";

function getDependencies(templateFileDir: string): string[] {
  const dTsFile = path.resolve(templateFileDir, 'dependencies.d.ts');
  const dTsContent = fs.readFileSync(dTsFile, 'utf-8');
  const dependencies = dTsContent.match(/declare module ["']([^']+)["']/g);
  return dependencies?.map(dep => dep.replace(/declare module ["']|["']/g, '')) || [];
}

let json: Record<string, any> | null = null;
function findPackageJson() {
  if (json) return json;
  const packageJsonPath = path.resolve('package.json');
  json = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
  if (!json) throw new Error('package.json not found');
  return json;
}

export function checkDependencies(templateFileDir: string): { missing: string[], has: string[] } {
  const dependencies = getDependencies(templateFileDir);
  const packageJson = findPackageJson();
  const missingDependencies = dependencies.filter(dep => !packageJson.dependencies[dep] && !packageJson.devDependencies[dep]);
  const hasDependencies = dependencies.filter(dep => packageJson.dependencies[dep] || packageJson.devDependencies[dep]);
  return { missing: missingDependencies, has: hasDependencies };
}